//: Playground - noun: a place where people can play

import Cocoa

typealias Filter = CIImage -> CIImage

//MARK: 高斯模糊
func blur(radius: Double) -> Filter {
    return { image in
        let parameters = [
            kCIInputRadiusKey: radius,
            kCIInputImageKey: image
        ]
        guard let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: parameters)
            else {
                fatalError()
        }
        guard let outputImage = filter.outputImage else { fatalError() }
        return outputImage
    }
}

//MAKR: 定义一个生成固定颜色的滤镜
func colorGenerator(color: NSColor) -> Filter {
    return { _ in
        guard let c = CIColor(color: color) else { fatalError() }
        let parameters = [ kCIInputColorKey: c]
        guard let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters) else { fatalError() }
        guard let outputImage = filter.outputImage else { fatalError() }
        return outputImage
    }
}

//: ### 定义合成滤镜

func composieSourceOver(overlay: CIImage) -> Filter {
    return { image in
        let parameters = [
            kCIInputBackgroundImageKey: image,
            kCIInputImageKey: overlay
        ]
        guard let filter = CIFilter(name: "CISourceOverCompositing", withInputParameters: parameters) else { fatalError() }
        guard let outputImage = filter.outputImage else { fatalError() }
        let cropRect = image.extent
        return outputImage.imageByCroppingToRect(cropRect)
        
    }
}

//: ### 通过结合两个滤镜创建颜色叠成滤镜
func colorOverlay(color: NSColor) -> Filter {
    return {
        image in
        let overlay = colorGenerator(color)(image)
        return composieSourceOver(overlay)(image)
    }
}

//: ### 定义组合滤镜组合函数
func composeFilters(filter1: Filter, _ filter2: Filter) -> Filter {
    return {
        image in
        filter2(filter1(image))
    }
}

let url = NSURL(string: "http://imgsrc.baidu.com/forum/w%3D580/sign=e1d8026d5dafa40f3cc6ced59b65038c/cb0d9dd4b31c870133a307b9207f9e2f0608ffd3.jpg")!
let image = CIImage(contentsOfURL: url)!
let blurRadius = 5.0
let overlayColor = NSColor.redColor().colorWithAlphaComponent(0.2)
let blurredImage = blur(blurRadius)(image)
let overlaidImage = colorOverlay(overlayColor)(blurredImage)

//: ### 通过滤镜组合函数合成图片
let result = composeFilters(colorOverlay(overlayColor), blur(blurRadius))(image)

//: ### 为组合滤镜自定义运算符 >>>
infix operator >>> { associativity left }
func >>> (filter1: Filter,filter2: Filter) -> Filter {
    return { image in filter2(filter1(image)) }
}

let myFilter = blur(blurRadius) >>> colorOverlay(overlayColor)
let result2 = myFilter(image)





